﻿# -*- coding:utf-8 -*-
#
# ГИМ
#
from django.shortcuts import render_to_response
from django.template import RequestContext, Context

from ktit.shm.models import Department, Employee, Phone



def recursive_get_department_list(department, level):
    res = []
    for di in department:
        item = {"id":di.id,"name":di.name,"parent":di.parent,"level":level,"csslevel":level*24,}
        department_set = di.department_set.all()
        item["child_present"] = department_set
        res.append(item)
        subdepartments=recursive_get_department_list(department_set, level+1)
        res.extend(subdepartments)
    return res



def create_department_tree():
    d = Department.objects.select_related().filter(parent=None)
    return recursive_get_department_list(d, 0)



def create_department_tree_ex(parent=None):
    d = Department.objects.select_related().filter(parent=parent)
    return recursive_get_department_list(d, 0)



def render_to(request, template, context):
    root_department = Department.objects.filter(parent=None)
    context_extra = Context({
        'root_department':root_department,
    })
    return render_to_response(template, context, context_instance=RequestContext(request, context_extra))



def index(request): 
    context = Context({
    })
    return render_to(request, 'shm/index.html', context)



def dep_list(request, department_id): 
    department = Department.objects.get(id=department_id)
    department_tree = create_department_tree_ex(parent=department)
    context = Context({
      'department': department,
      'department_tree':department_tree,
    })
    return render_to(request, 'shm/department_list.html', context)
    
    
    
def employee_list(request, root_department_id, department_id): 
    department =   Department.objects.get(id=root_department_id)  
    department_tree = create_department_tree_ex(parent=department)
    department_detail = Department.objects.get(id=department_id)  
    employee = Employee.objects.filter(department=department_detail)
    phone = department_detail.phone.all()
    boss = Employee.objects.get(department=department_detail, boss=True)
    context = Context({
      'department_detail': department_detail,
      'employee':employee,
      'phone':phone,
      'boss':boss,
      'department':department,
      'department_tree':department_tree,
    })
    return render_to(request, 'shm/employee_list.html', context)


